package ee.wm.ilmataat.xml;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import ee.wm.ilmataat.Station;

public class StationsXmlHandler extends DefaultHandler {

	Boolean currentElement;
	String currentValue;
	private List<Station> stations;
	private Station currentStation;

	public List<Station> getStations() {
		return stations;
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		currentElement = true;
		if (localName.equals("observations")) {
			stations = new ArrayList<Station>();
		} else if (localName.equals("station")) {
			currentStation = new Station();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		currentElement = false;
		if (localName.equalsIgnoreCase("name")) {
			currentStation.setName(currentValue);
		} else if (localName.equalsIgnoreCase("wmocode")) {
			currentStation.setWmoCode(currentValue);
		} else if (localName.equalsIgnoreCase("phenomenon")) {
			currentStation.setPhenomenon(currentValue);
		} else if (localName.equalsIgnoreCase("visibility")) {
			currentStation.setVisibility(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("precipitations")) {
			currentStation.setPrecipitations(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("airpressure")) {
			currentStation.setAirPressure(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("relativehumidity")) {
			currentStation.setRelativeHumidity(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("airtemperature")) {
			currentStation.setAirTemperature(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("winddirection")) {
			currentStation.setWindDirection(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("windspeed")) {
			currentStation.setWindSpeed(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("windspeedmax")) {
			currentStation.setWindSpeedMax(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("station")) {
			stations.add(currentStation);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (currentElement) {
			currentValue = new String(ch, start, length);
			currentElement = false;
		}
	}

}